package com.xing.crm.utils;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
public class ImageCompression {
    private Logger log = LoggerFactory.getLogger(getClass().getName());
    @Value("${photo.compression.width}")
    private String compressionWidth;

    private static void validateDimensions(int var0, int var1) {
        if (var0 <= 0 && var1 <= 0) {
            throw new IllegalArgumentException("Destination image dimensions must not be less than 0 pixels.");
        } else if (var0 <= 0 || var1 <= 0) {
            String var2 = var0 == 0 ? "width" : "height";
            throw new IllegalArgumentException("Destination image " + var2 + " must not be " + "less than or equal to 0 pixels.");
        }
    }

    //按坐标裁剪
    public void Crop(String i_path, String o_path) throws IOException {
        Thumbnails.of(i_path).sourceRegion(Positions.CENTER, 400, 400).size(200, 200).keepAspectRatio(false).toFile(new File(o_path));
    }

    /*
     * 指定大小,缩放,并输出倒原图上
     * size(width,height) 若图片横比200小，高比300小，不变
     * 若图片横比200小，高比300大，高缩小到300，图片比例不变 若图片横比200大，高比300小，横缩小到200，图片比例不变
     * 若图片横比200大，高比300大，图片按比例缩小，横为200或高为300
     */
    public String thumbnail(String i_path, String o_path) throws IOException {

        List<String> strings = Arrays.asList("avi", "flv", "mpg", "mpeg", "mpe", "m1v", "m2v", "mpv2", "mp2v", "dat", "ts", "tp", "tpr", "pva", "pss", "mp4", "m4v", "m4p", "m4b", "3gp", "3gpp", "3g2", "3gp2", "ogg", "mov", "qt", "amr", "rm", "ram", "rmvb", "rpm");
        String finalI_path = i_path;
        AtomicBoolean isVideo = new AtomicBoolean(false);
        strings.forEach(i -> {
            if (finalI_path.contains(i.toLowerCase()) == true) isVideo.set(true);
        });
        if (isVideo.get()) {
            log.info("上传文件，发现是视频文件，停止照片压缩：{},{}", i_path, o_path);
            return new File(i_path).getName();
        }

        //获取照片宽高
        FileInputStream stream = new FileInputStream(o_path);
        BufferedImage read = ImageIO.read(stream);
        int w = read.getWidth();
        int h = read.getHeight();
        stream.close();

        //获取设置的缩放宽高
        int i = Integer.parseInt(compressionWidth);

        //转换jpg
        if (i_path.contains(".png") || i_path.contains(".PNG")) {
            String png = i_path;
            //改变为新的jpg路径
            i_path = imgFormat(i_path, o_path, w, h, "jpg");

            //删除已上传png照片
            new File(png).getAbsoluteFile().delete();
            //往原图上输出
            o_path = i_path;
        }

        //压缩品质并输出
        Thumbnails.of(i_path).size(i, h).outputQuality(0.7f).toFile(new File(o_path));
        return new File(i_path).getName();
    }

    //转jpg返回jpg地址
    public static String imgFormat(String source, String output, int w, int h, String format) throws IOException {
        //如果是png，就转换jpg，并返回路径
        Thumbnails.Builder<File> fileBuilder = Thumbnails.of(source).size(w, h).outputFormat(format);
        fileBuilder.toFile(output);
        return source + ".jpg";
    }

    //不按照比例，指定大小,缩放
    public void thumbnailSize(String i_path, String o_path) throws IOException {
        Thumbnails.of(i_path).size(200, 200).keepAspectRatio(false).toFile(o_path);
    }

    //按比例缩放,1原型 越小愈模糊
    public void scaleProportionally(String i_path, String o_path) throws IOException {
        Thumbnails.of(i_path).scale(0.25f).toFile(o_path);
    }

    //旋转,按角度
    public void Spin(String i_path, String o_path) throws IOException {
        Thumbnails.of(i_path).size(1280, 1024).rotate(90).toFile(o_path);
    }

    //水印
    public void watermark(String i_path, String watermark, String o_path) throws IOException {
        Thumbnails.of(i_path).size(1280, 1024).
                watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(watermark)), 0.5f).
                outputQuality(0.8f).toFile(o_path);
    }

}
